package com.ggb.multiplebackstackscomposestudy

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.ggb.multiplebackstackscomposestudy.ui.theme.MultipleBackstacksComposeStudyTheme

class MainActivity : ComponentActivity() {
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MultipleBackstacksComposeStudyTheme {
                //处理应用程序内的导航
                val rootNavController = rememberNavController()
                // 这行代码从NavController中获取当前的返回栈条目，并创建一个状态，以便在返回栈发生变化时自动更新
                val navBackStackEntry by rootNavController.currentBackStackEntryAsState()

                Scaffold(
                    bottomBar = {
                        NavigationBar {
                            items.forEach { item ->
                                // 这行代码通过将当前项的标题（转换为小写）与返回栈中当前目的地的路由进行比较来检查当前项是否被选中。
                                // 如果它们匹配，则表示该项被选中。
                                val isSelected =
                                    item.title.lowercase() == navBackStackEntry?.destination?.route
                                NavigationBarItem(
                                    selected = isSelected,
                                    onClick = {
                                        rootNavController.navigate(item.title.lowercase()) {
                                            /**
                                             * 这部分代码定义了导航时的返回栈行为。它指定了要弹出到的目标位置，即返回栈中的一个目的地。
                                             * 在这里，rootNavController.graph.findStartDestination().id找到了导航图的起始目的地，
                                             * 并将其作为弹出目标。
                                             */
                                            popUpTo(rootNavController.graph.findStartDestination().id) {
                                                // 表示弹出到目标位置时，保存目标位置及其状态
                                                saveState = true
                                            }
                                            // 如果导航目标已经在返回栈的栈顶，则不会创建一个新的实例，而是重用已存在的实例。
                                            launchSingleTop = true
                                            /**
                                             * 这个参数指定了在导航到目标时是否应该恢复目标的状态。
                                             * 如果目标之前已经被创建并保存了其状态，那么在导航到目标时会尝试恢复该状态。
                                             * 这对于保持导航目标的状态一致性很有用。
                                             */
                                            restoreState = true
                                        }
                                    },
                                    icon = {
                                        Icon(
                                            imageVector = if (isSelected) item.selectedIcon else item.unselectedIcon,
                                            contentDescription = null
                                        )
                                    })
                            }
                        }
                    }
                ) { paddingValues ->
                    Box(modifier = Modifier.padding(paddingValues)) {
                        NavHost(navController = rootNavController, startDestination = "home") {
                            composable("home") {
                                HomeNavHost()
                            }
                            composable("chat") {
                                ChatNavHost()
                            }
                            composable("settings") {
                                SettingsNavHost()
                            }
                        }
                    }

                }
            }
        }
    }
}


@Composable
fun HomeNavHost() {
    val homeNavController = rememberNavController()
    NavHost(navController = homeNavController, startDestination = "home1") {
        for (i in 1..10) {
            composable("home${i}") {
                GenericScreen(text = "Home${i}") {
                    homeNavController.navigate("home${i+1}")
                }
            }
        }
    }
}

@Composable
fun ChatNavHost() {
    val chatNavController = rememberNavController()
    NavHost(navController = chatNavController, startDestination = "chat1") {
        for (i in 1..10) {
            composable("chat${i}") {
                GenericScreen(text = "Chat${i}") {
                    chatNavController.navigate("chat${i+1}")
                }
            }
        }
    }
}

@Composable
fun SettingsNavHost() {
    val settingsNavController = rememberNavController()
    NavHost(navController = settingsNavController, startDestination = "settings1") {
        for (i in 1..10) {
            composable("settings${i}") {
                GenericScreen(text = "Settings${i}") {
                    settingsNavController.navigate("settings${i+1}")
                }
            }
        }
    }
}

@Composable
fun GenericScreen(text: String, onNextClick: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(text = text)
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = onNextClick) {
            Text(text = "next")
        }
    }
}


// 数据定义

data class BottomNavigationItem(
    val title: String,
    val unselectedIcon: ImageVector,
    val selectedIcon: ImageVector
)

val items = listOf(
    BottomNavigationItem(
        title = "Home",
        selectedIcon = Icons.Filled.Home,
        unselectedIcon = Icons.Outlined.Home
    ),
    BottomNavigationItem(
        title = "Chat",
        selectedIcon = Icons.Filled.Email,
        unselectedIcon = Icons.Outlined.Email
    ),
    BottomNavigationItem(
        title = "Settings",
        selectedIcon = Icons.Filled.Settings,
        unselectedIcon = Icons.Outlined.Settings
    )
)